package com.ifinc.common.socket.netty.server;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-30
 * Time: 00:47
 */

import com.ifinc.common.socket.netty.ContextConfig;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * 消息处理类
 */
public class ServerMessageHandler extends SimpleChannelHandler {

    private ContextConfig contextConfig;

    public ServerMessageHandler(ContextConfig contextConfig) {
        super();
        this.contextConfig = contextConfig;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
            throws Exception {
        System.out.println("e.getMessage():" + e.getMessage());
        ChannelBuffer buf = (ChannelBuffer) e.getMessage();
        byte[] input = buf.array();
        String param = new String(input);
        System.out.println("param = " + param);
        ChannelBuffer channelBuffer = ChannelBuffers.buffer(100);
        channelBuffer.writeBytes("OK".getBytes());
        e.getChannel().write(channelBuffer);
        if (!contextConfig.isConnection()) {
            e.getChannel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {

//        super.exceptionCaught(ctx, e);
        System.out.println(e.getCause());

    }

}
